<template>
    <div>
        <div class="bg-left">
            <el-upload class="upload-demo" :action="imagesUrl" :on-success="handleSuccess" :on-preview="handlePreview" :on-remove="handleRemove" :file-list="fileList" :before-upload="beforeAvatarUpload" list-type="picture">
                <el-button size="small" type="primary">点击上传</el-button>
                <div slot="tip" class="el-upload__tip">只能上传jpg/png文件，且不超过500kb</div>
            </el-upload>
        </div>
    </div>
</template>

<script>
export default {
    data() {
        return {
            imagesUrl: this.ajaxUrl() + "/index/image",
            fileList: []
        }
    },
    props: {
        src: ""
    },
    watch: {
        src() {
            if (typeof this.src == "string") {
                if (this.src.length != 0) {
                    let img = eval('(' + this.src + ')');

                    if (img.length != 0) {
                        img.forEach((n) => {
                            this.fileList.push(n)
                        });
                    }
                } else {
                    this.fileList = [];
                }
            }
        }
    },
    methods: {
        handleRemove(file, fileList) {
            this.fileList = fileList;
            // this.$http.get(this.ajaxUrl() + "/api/tool/imgRecycle", {
            //     params: {
            //         oldImgUrl: file.url
            //     }
            // }).then((res) => {
            //     this.fileList = fileList;
            // })
        },
        handlePreview(file) {
        },
        handleSuccess(res, file, fileList) {
            this.fileList.push({
                name: file.name,
                url: this.ajaxUrl() + "/images" + file.response.msg
            })
        },
        beforeAvatarUpload(file) {
            const isLt2M = file.size / 1024 / 1024 < 2;

            if (file.type != 'image/jpeg' && file.type != 'image/png') {
                this.$message.error('上传头像图片只能是 JPG 格式!');
            }
            if (!isLt2M) {
                this.$message.error('上传头像图片大小不能超过 2MB!');
            }
            return isLt2M;
        },
    }
}
</script>

<style>
.el-upload-list--picture .el-upload-list__item {
    width: 300px;
    display: block;
    float: left;
    margin-right: 20px;
}

.el-upload-list {
    overflow: hidden;
    width: 800px;
}
</style>